var vue2editor = {
    data: function() {
        return {
            editorContent: "",
            editorHeight: "auto",
           // editorContentPreview: "",
           // editorUploadUrl: "../../../../pub/attach/uploadsingle",
            editorUploadUrl: "/pub/attach/uploadsingle",
            // htmlPreviewShow: false, //html预览
            titleConfig: [
				{Choice:'.ql-bold',title:'加粗'},
				{Choice:'.ql-italic',title:'斜体'},
				{Choice:'.ql-underline',title:'下划线'},
				{Choice:'.ql-header',title:'段落格式'},
				{Choice:'.ql-strike',title:'删除线'},
				{Choice:'.ql-blockquote',title:'块引用'},
				{Choice:'.ql-code',title:'插入代码'},
				{Choice:'.ql-code-block',title:'插入代码段'},
				{Choice:'.ql-font',title:'字体'},
				{Choice:'.ql-size',title:'字体大小'},
				{Choice:'.ql-list[value="ordered"]',title:'编号列表'},
				{Choice:'.ql-list[value="bullet"]',title:'项目列表'},
				{Choice:'.ql-direction',title:'文本方向'},
				{Choice:'.ql-header[value="1"]',title:'h1'},
				{Choice:'.ql-header[value="2"]',title:'h2'},
				//{Choice:'.ql-align',title:'对齐方式'},
				{Choice:'.ql-color',title:'字体颜色'},
				{Choice:'.ql-background',title:'背景颜色'},
				{Choice:'.ql-image',title:'图像'},
				{Choice:'.ql-video',title:'视频'},
				{Choice:'.ql-link',title:'添加链接'},
				{Choice:'.ql-formula',title:'插入公式'},
				{Choice:'.ql-clean',title:'清除字体格式'},
				{Choice:'.ql-script[value="sub"]',title:'下标'},
				{Choice:'.ql-script[value="super"]',title:'上标'},
				{Choice:'.ql-indent[value="-1"]',title:'向左缩进'},
				{Choice:'.ql-indent[value="+1"]',title:'向右缩进'},
				{Choice:'.ql-header .ql-picker-label',title:'标题大小'},
				{Choice:'.ql-header .ql-picker-item[data-value="1"]',title:'标题一'},
				{Choice:'.ql-header .ql-picker-item[data-value="2"]',title:'标题二'},
				{Choice:'.ql-header .ql-picker-item[data-value="3"]',title:'标题三'},
				{Choice:'.ql-header .ql-picker-item[data-value="4"]',title:'标题四'},
				{Choice:'.ql-header .ql-picker-item[data-value="5"]',title:'标题五'},
				{Choice:'.ql-header .ql-picker-item[data-value="6"]',title:'标题六'},
				{Choice:'.ql-header .ql-picker-item:last-child',title:'标准'},
				{Choice:'.ql-size .ql-picker-item[data-value="small"]',title:'小号'},
				{Choice:'.ql-size .ql-picker-item[data-value="large"]',title:'大号'},
				{Choice:'.ql-size .ql-picker-item[data-value="huge"]',title:'超大号'},
				{Choice:'.ql-size .ql-picker-item:nth-child(2)',title:'标准'},
				{Choice:'.ql-align:first-child',title:'居左对齐'},
				{Choice:'.ql-align[value="center"]',title:'居中对齐'},
				{Choice:'.ql-align[value="right"]',title:'居右对齐'},
				{Choice:'.ql-align[value="justify"]',title:'两端对齐'},
				{Choice:'.ql-htmlpreview',title:'显示/隐藏html预览'},
				{Choice:'.ql-htmlcode',title:'编辑源代码'},
				{Choice:'.ql-videoupload', title: "上传视频文件"}
			],            
            editorSettings: {
                modules: {
                    imageDrop: true,
                    imageResize: {},
                    videoResize: {},
                    toolbar: {
                        container: [
                            [{
                                header: [false, 1, 2, 3, 4, 5, 6]
                            }],
                            ["bold", "italic", "underline", "strike", {
                                size:  [  '12px', false, '14px', '16px' ,'18px', '20px', '22px', '24px', '26px', '32px', '48px'] 
                            }], // toggled buttons
                            [{
                                align: ""
                            }, {
                                align: "center"
                            }, {
                                align: "right"
                            }, {
                                align: "justify"
                            }],
                            ["blockquote"], //  "code-block"
                            [{
                                list: "ordered"
                            }, {
                                list: "bullet"
                            }],
                            [{
                                indent: "-1"
                            }, {
                                indent: "+1"
                            }], // outdent/indent
                            [{
                                color: []
                            }, {
                                background: []
                            }], // dropdown with defaults from theme
                            ["link", "image", "video", "videoupload"], 
                            ["htmlcode"],
                            ["clean"] // remove formatting button
                        ],
                        handlers: {
                            videoupload: function() {
                                var upBtn = document.querySelector("#video-upload");
                                if (!upBtn) {
                                    upBtn = document.createElement("input");
                                    upBtn.setAttribute("id", "video-upload");
                                    upBtn.setAttribute("type", "file");
                                    upBtn.setAttribute("accept", "video/*");
                                    upBtn.setAttribute("style", "display: none;");
                                    document.querySelector(".quillWrapper").appendChild(upBtn);
                                    var that = this;
                                    upBtn.addEventListener("change", function($event) {
                                        var resetUploader = function resetUploader() {
                                            upBtn.value = "";
                                        };
                                        var file = $event.target.files[0];
                                        var Editor = that.quill;
                                        var range = Editor.getSelection();
                                        var cursorLocation = range.index;
                                        // console.log(that)
                                        //that.$emit("video-added", file, Editor, cursorLocation, resetUploader);   
                                        vueApp.handleImageAdded(file, Editor, cursorLocation, resetUploader)
                                    })
                                }
                                upBtn.click();
                            },
                            htmlcode: function() {
                                vueApp.$showEditorCode(vueApp.editorContent).then(function(s){
                                	console.log(s)
                                	vueApp.editorContent = s;
                                });
                            }
                        }
                    },
                }
            }
        };
    },
    mounted: function() {
    	this.setButtonTip();
    	this.setLinkDialog();
    	this.setEditorHeight();
    },
    methods: {
    	//链接，视频提前判断，return  就不调用 origin.call(this); 
    	setLinkDialog: function() {
    		this.$refs.edt.quill.theme.tooltip.save = (function(origin){
  			    return function(){
  			      var value = this.textbox.value;
  			      var type = this.root.getAttribute('data-mode');
  			      console.log(value, type);
  			    
  			      if(type == "link") {
  			    	  
  			      }
  			      else if(type == "video") {
  			    	  
  			      }  			      
  			      origin.call(this); 
  			    }
  			  })(this.$refs.edt.quill.theme.tooltip.save)    		
    	},
    	setEditorHeight: function() {
    		var n = parseFloat(this.editorHeight);
    		n = n ? n + "px" : "auto";
    		this.$refs.edt.$el.querySelector("#editor").setAttribute("style", "height:" + this.editorHeight + "px;")
    	},
    	setButtonTip: function() {
		      for(var i = 0; i < this.titleConfig.length; i++){
		    	      var item = this.titleConfig[i];
			          var tip = document.querySelector('.ql-toolbar '+ item.Choice)
			          if (!tip) 
			        	  continue;
			          tip.setAttribute('title',item.title)
			   }  		
    	},
        formatFontSize: function(s){
            var con = document.createElement("div");
            con.innerHTML = s;
            var arr = con.querySelectorAll("span[class^='ql-size-']");
            for(var i = 0; i < arr.length; i++) {
              var c = arr[i].getAttribute("class");
              c = c.replace("ql-size-", "");
              arr[i].style.cssText += ("font-size:" + c + ";");
              arr[i].removeAttribute("class");
            }
            return con.innerHTML;
        },    	
        getRootPath: function() {
            // 1、获取当前全路径，如： http://localhost:8080/springmvc/page/frame/test.html
            var curWwwPath = window.location.href;
            // 获取当前相对路径： /springmvc/page/frame/test.html
            var pathName = window.location.pathname; // 获取主机地址,如： http://localhost:8080
            var local = curWwwPath.substring(0, curWwwPath.indexOf(pathName));
            // 获取带"/"的项目名，如：/springmvc  
            var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
            var rootPath = local + projectName;
            return rootPath;
        },
        handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
            console.log(file);
            var that = this;
            var fileData = new FormData();
            fileData.append("file", file);
            fileData.append("fileName", file.name);
            fileData.append("modeName", "富文本上传");
            fileData.append("folder", "file/other");
            fileData.append("fileType", file.type);
            fileData.append("fileSize", file.size);
            var that = this;          
            axios.post(this.getRootPath() +this.editorUploadUrl, fileData, {
            	onUploadProgress: function(progressEvent) {
                    var complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
                    that.$showProgress(complete);
                },
                headers: {
                    "content-type": "multipart/form-data"
                }
            }).then(function(res) {
            	that.$showProgress(false);
                console.log(res);
                console.log(that.getRootPath());
                var url = that.getRootPath() + "/" + res.data.fileList[0].filePath;
                console.log(url);
                console.log(file.type);
                if (file.type.indexOf("image") >= 0) {
                    Editor.insertEmbed(cursorLocation, 'image', url);
                } else if (file.type.indexOf("video") >= 0) {
                    Editor.insertEmbed(cursorLocation, 'video', url);
                } else {

                }
                resetUploader();
            });
        },

    },
//    watch: {
//        editorContent:{
//            handler:(function(){
//            	var timer;
//                return function(val,oldval){
//                	var that = this;
//              	    if(timer) {
//              	    	clearTimeout(timer);
//              	    	timer = null;
//              	    }
//              	    timer = setTimeout(function(){
//              	    	that.editorContentPreview = that.formatFontSize(val)
//              	    }, 1000);
//                }
//            })()
//        }
//    }
}

;(function(){
	  var com = Vue.component('code-dialog', {
		    template: '<div v-cloak> '+
		    '  <el-dialog '+
		    '    title="编辑源码" '+
		    '    :close-on-press-escape="false"  '+
		    '    :close-on-click-modal="false"  '+
		    '    :show-close="false" '+
		    '    :visible.sync="dialogVisible" '+
		    '    width="700px"> '+
		    '    <div class="c-editor-codecontent"> '+
		    '      <textarea class="c-editor-codetext" v-model="content"></textarea> '+
		    '    </div> '+
		    '    <span slot="footer" class="dialog-footer"> '+
		    '      <el-button @click="onCancel">取 消</el-button> '+
		    '      <el-button type="primary" @click="onOk">确 定</el-button> '+
		    '    </span> '+
		    '  </el-dialog>'+
		    '</div> ',
		    data: function () {
		      return {
	            dialogVisible: false,
	            content: "",
	            rs: null
		      }
		    }, 
		    mounted: function(){
		    },    
		    methods: {
	    	  show: function(txt) {
	            this.content = txt;
	            this.dialogVisible = true;
	            var that = this;
	            return new Promise(function(rs, rj){
	              that.rs = rs;  
	            })
	          },
	          reset: function() {
	            this.content = "";
	            this.rs = null;
	          },
	          onCancel: function(){
	            this.reset();
	            this.dialogVisible = false;
	          },
	          onOk: function() {
	            var s = this.content;
	            this.rs(s);
	            this.reset();
	            this.dialogVisible = false;
	          }
		    }
		  })    
		  var object = new com()
		  object.$mount()
		  document.body.appendChild(object.$el)
		  Vue.prototype.$showEditorCode = object.show 
})()